package com.zhijiang.hospital.controller;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.EasyExcel;
import com.auth0.jwt.JWT;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.zhijiang.common.config.result.MyException;
import com.zhijiang.common.config.result.ResponseEnum;
import com.zhijiang.common.util.*;
import com.zhijiang.common.util.QRCode.QRCodeUtil;
import com.zhijiang.common.util.file.FileUtil;
import com.zhijiang.common.util.redis.RedisService;
import com.zhijiang.hospital.entrty.ComEmployee;
import com.zhijiang.hospital.entrty.Meeting;
import com.zhijiang.hospital.entrty.OutsideEmployee;
import com.zhijiang.hospital.entrty.SMeetingcheckrecode;
import com.zhijiang.hospital.entrty.dto.CountDto;
import com.zhijiang.hospital.entrty.dto.EmployeeDto;
import com.zhijiang.hospital.entrty.dto.MeetingEmployeeDto;
import com.zhijiang.hospital.service.DeptService;
import com.zhijiang.hospital.service.EmployeeDtoService;
import com.zhijiang.hospital.service.MeetingCheckRecodeService;
import com.zhijiang.hospital.service.MeetingEmployeeService;
import com.zhijiang.hospital.service.MeetingService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.text.ParseException;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;


/**
 * @author 75936
 * @version 1.0
 * @project zhiJiangHealthBureau
 * @description
 * @date 2023-01-10 09:21:32
 */
@Slf4j
@Component
@RestController
@RequestMapping("meeting")
public class MeetingController {
    @Autowired
    RedisService redisService;
    @Autowired
    private MeetingService meetingService;
    @Autowired
    private EmployeeDtoService employeeDtoService;
    @Autowired
    DeptService deptService;
    @Autowired
    MeetingEmployeeService meetingEmployeeService;

    @GetMapping("findAll")
    public ApiResult findAllMeeting(BaseQuery baseQuery) {
        return ApiResult.ok(meetingService.findAll(baseQuery));
    }

    /**
     * 范
     * @param mName
     * @param mAddress
     * @param mBeginDate
     * @param
     * @param mEndDate
     * @param mRemark1
     * @param mRemark2
     * @param mRemark3
     * @param dto
     * @return
     */
    @PostMapping("/insert")
    @Transactional
    public ApiResult insert(
            @RequestParam("mName") String mName,
            @RequestParam("mAddress") String mAddress,
            @RequestParam("mBeginDate") String mBeginDate,
            @RequestParam("mEndDate") String mEndDate,
            @RequestParam("timeCode") String timeCode,
            String mRemark1,
            String mRemark2,
            String mRemark3,
            @RequestBody List<MeetingEmployeeDto> dto,
            HttpServletRequest request) throws ParseException {
        String token = request.getHeader("token");
        String emplCode;
        try {
            emplCode = JWT.decode(token).getAudience().get(0);
        } catch (JWTDecodeException e) {
            throw new MyException(ResponseEnum.TOKEN_EX.getCode(), ResponseEnum.TOKEN_EX.getResultMessage());
        }
        Meeting meeting = new Meeting();
        meeting.setMName(mName);
        meeting.setMAddress(mAddress);
        meeting.setMValidity("1");
        meeting.setMBeginDate(Convert.toDate(mBeginDate));
        meeting.setMRemark1(mRemark1);
        meeting.setMRemark2(timeCode);
        meeting.setMRemark1(mRemark3);
        ComEmployee c =  deptService.get(emplCode);
        if (Objects.isNull(c)){
            throw new RuntimeException("不是职工无法创建会议");
        }
        meeting.setMOperName(c.getEmplName());

        Date date = new Date();
        Date parse = DateUtil.parse(date.toString());
        meeting.setMOperDate(parse);
        meeting.setMEndDate(Convert.toDate(mEndDate));
        String s = NumberUtil.toNumber(meeting.getMBeginDate());
        List<String> mCodeList = meetingService.findMCode(s);
        if (mCodeList.isEmpty()) {
            meeting.setMCode(s + "0001");
        } else {
            String max = Collections.max(mCodeList);
            Long aLong = Long.valueOf(max);
            aLong = aLong + 1L;
            String s1 = String.valueOf(aLong);
            meeting.setMCode(s1);
        }
        meeting.setMOperCode(emplCode);
        Integer integer = meetingService.insertMeeting(meeting);
        if (integer > 0) {
            String s1 = RandomUtil.randomNumbers(4);
            meetingEmployeeService.insertEmployee(dto,meeting.getMCode(),mName,Convert.toDate(mBeginDate),Convert.toDate(mEndDate),mAddress);
            return ApiResult.ok(QRCodeUtil.getCode(meeting.getMCode() + "/" + s1), "会议添加成功");
        } else {
            return ApiResult.fail("会议添加失败");
        }
    }



    @GetMapping("/insertMeeting")
    public ApiResult insertMeeting(
            @RequestParam("mName") String mName,
            @RequestParam("mAddress") String mAddress,
            @RequestParam("mBeginDate") String mBeginDate,
            @RequestParam("mOperName") String mOperName,
            @RequestParam("mEndDate") String mEndDate,
            @RequestBody List<MeetingEmployeeDto> dto,
            String mRemark1,
            String mRemark2,
            String mRemark3
    ) {
        Meeting meeting = new Meeting();
        meeting.setMName(mName);
        meeting.setMAddress(mAddress);
        meeting.setMValidity("1");
        meeting.setMBeginDate(Convert.toDate(mBeginDate));
        meeting.setMRemark1(mRemark1);
        meeting.setMRemark1(mRemark2);
        meeting.setMRemark1(mRemark3);
        meeting.setMOperName(mOperName);
        Date date = new Date();
        Date parse = DateUtil.parse(date.toString());
        meeting.setMOperDate(parse);
        meeting.setMEndDate(Convert.toDate(mEndDate));
        String s = NumberUtil.toNumber(meeting.getMBeginDate());
        List<String> mCodeList = meetingService.findMCode(s);
        if (mCodeList.isEmpty()) {
            meeting.setMCode(s + "0001");
        } else {
            String max = Collections.max(mCodeList);
            Long aLong = Long.valueOf(max);
            aLong = aLong + 1L;
            String s1 = String.valueOf(aLong);
            meeting.setMCode(s1);
        }
        Integer integer = meetingService.insertMeeting(meeting);
        if (integer > 0) {
            String s1 = RandomUtil.randomNumbers(4);
            redisService.setStringKeyAndValue(meeting.getMCode(), s1);
            return ApiResult.ok(QRCodeUtil.getCode(meeting.getMCode() + "/" + s1), "会议添加成功");
        } else {
            return ApiResult.fail("会议添加失败");
        }
    }
    @Autowired //StringRedisTemplate它是redisTemplate的子类，而且独有特点：它保存的数据key和value都是string
    private StringRedisTemplate stringRedisTemplate;
    @GetMapping("getCode")
    public ApiResult getCode(@RequestParam("mCode") String mCode) {
        Meeting meeting = meetingService.selectMeeting(mCode);

        //二维码作废间隔
        int i = Integer.parseInt(meeting.getMRemark2());
        Long l=Long.parseLong(meeting.getMRemark2());//返回基本数据类型long

        //二维码存在时间
       Long expire = stringRedisTemplate.getExpire(mCode+meeting.getMKey());


        if (ObjectUtil.isEmpty(meeting)) {
            return ApiResult.fail("暂无会议信息");
        }
        if (meeting.getMFlushed()==0){
            meeting.setMFlushed(30);
        }
        int mFlushed = meeting.getMFlushed();


        String keyObjectValue = redisService.getKeyObjectValue(mCode+meeting.getMKey(), String.class);

        if (expire>l){
            meeting.setQRCode(QRCodeUtil.getCode(mCode+ "/"+keyObjectValue+ "," +meeting.getMName()));
            return  ApiResult.ok(meeting);
        }else {
            String s = RandomUtil.randomNumbers(4);
            meetingService.update1(mCode,s);
            redisService.setStringKeyAndValueSECONDS(mCode+s, s,i+mFlushed);
            meeting.setQRCode(QRCodeUtil.getCode(mCode + "/" + s + "," + meeting.getMName()));

            return ApiResult.ok(meeting);
        }
    }
    @Autowired
    MeetingCheckRecodeService meetingCheckRecodeService;
    @GetMapping("findSignEmployee")
    public ApiResult findSignEmployee(String mCode){
        List<SMeetingcheckrecode> singInEmployee = meetingCheckRecodeService.findSignEmployee(mCode);
        for (SMeetingcheckrecode sMeetingcheckrecode : singInEmployee) {
                    if(    sMeetingcheckrecode.getPValidity().equals("1")){
                        sMeetingcheckrecode.setPValidity("已签到");
                    }else if (sMeetingcheckrecode.getPValidity().equals("0")){
                        sMeetingcheckrecode.setPValidity("未签到");
                    }else  if(sMeetingcheckrecode.getPValidity().equals("2")){
                        sMeetingcheckrecode.setPValidity("迟到");
                    }else if (sMeetingcheckrecode.getPValidity().equals("3")){
                        sMeetingcheckrecode.setPValidity("请假");
                    }else if (sMeetingcheckrecode.getPValidity().equals("5")){
                        sMeetingcheckrecode.setPValidity("审批中");
                    }
        }
        Stream<SMeetingcheckrecode> sorted = singInEmployee.stream().sorted(Comparator.comparing(SMeetingcheckrecode::getMBegindate, Comparator.nullsLast(Comparator.reverseOrder())));
        if (singInEmployee.isEmpty()) {
            return ApiResult.fail("暂无签到员工");
        } else {
            return ApiResult.ok(sorted);
        }
    }
    /**
     * 已签到接口
     * fan
     */
    @GetMapping("findAlreadySignEmployee")
    public ApiResult findAlreadySignEmployee(String mCode){
        System.out.println(mCode);
        List<SMeetingcheckrecode> singInEmployee = meetingCheckRecodeService.findSignEmployee(mCode);

        for (SMeetingcheckrecode sMeetingcheckrecode : singInEmployee) {
            System.out.println(sMeetingcheckrecode.getPValidity());
            if(    sMeetingcheckrecode.getPValidity().equals("1")){
                sMeetingcheckrecode.setPValidity("已签到");
            }else if (sMeetingcheckrecode.getPValidity().equals("0")){
                sMeetingcheckrecode.setPValidity("未签到");
            }else  if(sMeetingcheckrecode.getPValidity().equals("2")){
                sMeetingcheckrecode.setPValidity("迟到");
            }else if (sMeetingcheckrecode.getPValidity().equals("3")){
                sMeetingcheckrecode.setPValidity("请假");
            }else if (sMeetingcheckrecode.getPValidity().equals("5")){
                sMeetingcheckrecode.setPValidity("审批中");
            }
        }
        Stream<SMeetingcheckrecode> notSign = singInEmployee.stream().filter(s -> s.getPValidity().equals("已签到")||s.getPValidity().equals("二次签到"));
        if (singInEmployee.isEmpty()) {
            return ApiResult.fail("暂无迟到员工");
        } else {
            return ApiResult.ok(notSign);
        }
    }
    /**
     * 已签到接口
     * fan
     */
    @GetMapping("findAlreadySignEmployeeCount")
    public ApiResult findAlreadySignEmployeeCount(String mCode){
        System.out.println(mCode);
        List<SMeetingcheckrecode> singInEmployee = meetingCheckRecodeService.findSignEmployee(mCode);

        for (SMeetingcheckrecode sMeetingcheckrecode : singInEmployee) {
            System.out.println(sMeetingcheckrecode.getPValidity());
            if(    sMeetingcheckrecode.getPValidity().equals("1")){
                sMeetingcheckrecode.setPValidity("已签到");
            }else if (sMeetingcheckrecode.getPValidity().equals("0")){
                sMeetingcheckrecode.setPValidity("未签到");
            }else  if(sMeetingcheckrecode.getPValidity().equals("2")){
                sMeetingcheckrecode.setPValidity("迟到");
            }else if (sMeetingcheckrecode.getPValidity().equals("3")){
                sMeetingcheckrecode.setPValidity("请假");
            }else if (sMeetingcheckrecode.getPValidity().equals("5")){
                sMeetingcheckrecode.setPValidity("审批中");
            }
        }

        //已到
        long arrivedCount = singInEmployee.stream().filter(s -> s.getPValidity().equals("已签到") || s.getPValidity().equals("二次签到") || s.getPValidity().equals("迟到")).count();
        //未到
        long noArrivedCount    = singInEmployee.stream().filter(s -> s.getPValidity().equals("未签到") || s.getPValidity().equals("审批中") || s.getPValidity().equals("请假")).count();
        //应到
        long allCount = singInEmployee.size();
        CountDto countDto = new CountDto();

        countDto.setAllCount(allCount);
        countDto.setArrivedCount(arrivedCount);
        countDto.setNoArrivedCount(noArrivedCount);
        if (singInEmployee.isEmpty()) {
            return ApiResult.fail("暂无迟到员工");
        } else {
            return ApiResult.ok(countDto);
        }
    }
    /**
     * 迟到接口
     * fan
     */

    @GetMapping("findLateSignEmployee")
    public ApiResult findLateSignEmployee(String mCode){
        System.out.println(mCode);
        List<SMeetingcheckrecode> singInEmployee = meetingCheckRecodeService.findSignEmployee(mCode);
        for (SMeetingcheckrecode sMeetingcheckrecode : singInEmployee) {
            System.out.println(sMeetingcheckrecode.getPValidity());
            if(    sMeetingcheckrecode.getPValidity().equals("1")){
                sMeetingcheckrecode.setPValidity("已签到");
            }else if (sMeetingcheckrecode.getPValidity().equals("0")){
                sMeetingcheckrecode.setPValidity("未签到");
            }else  if(sMeetingcheckrecode.getPValidity().equals("2")){
                sMeetingcheckrecode.setPValidity("迟到");
            }else if (sMeetingcheckrecode.getPValidity().equals("3")){
                sMeetingcheckrecode.setPValidity("请假");
            }else if (sMeetingcheckrecode.getPValidity().equals("5")){
                sMeetingcheckrecode.setPValidity("审批中");
            }
        }
        Stream<SMeetingcheckrecode> notSign = singInEmployee.stream().filter(s -> s.getPValidity().equals("迟到"));
        if (singInEmployee.isEmpty()) {
            return ApiResult.fail("暂无迟到员工");
        } else {
            return ApiResult.ok(notSign);
        }
    }
    /**
     * 未到接口
     * fan
     */
    @GetMapping("findNotSignEmployee")
    public ApiResult findNotSignEmployee(String mCode){
        List<SMeetingcheckrecode> singInEmployee = meetingCheckRecodeService.findSignEmployee(mCode);
        for (SMeetingcheckrecode sMeetingcheckrecode : singInEmployee) {
            if(    sMeetingcheckrecode.getPValidity().equals("1")){
                sMeetingcheckrecode.setPValidity("已签到");
            }else if (sMeetingcheckrecode.getPValidity().equals("0")){
                sMeetingcheckrecode.setPValidity("未签到");
            }else  if(sMeetingcheckrecode.getPValidity().equals("2")){
                sMeetingcheckrecode.setPValidity("迟到");
            }else if (sMeetingcheckrecode.getPValidity().equals("3")){
                sMeetingcheckrecode.setPValidity("请假");
            }else if (sMeetingcheckrecode.getPValidity().equals("5")){
                sMeetingcheckrecode.setPValidity("审批中");
            }
        }
        Stream<SMeetingcheckrecode> notSign = singInEmployee.stream().filter(s -> s.getPValidity().equals("未签到"));
        if (singInEmployee.isEmpty()) {
            return ApiResult.fail("暂无迟到员工");
        } else {
            return ApiResult.ok(notSign);
        }
    }
    /**
     * 未到接口
     * fan
     */
    @GetMapping("findApprovalEmployee")
    public ApiResult findApprovalEmployee(String mCode){
        System.out.println(mCode);
        List<SMeetingcheckrecode> singInEmployee = meetingCheckRecodeService.findSignEmployee(mCode);
        for (SMeetingcheckrecode sMeetingcheckrecode : singInEmployee) {
            if(    sMeetingcheckrecode.getPValidity().equals("1")){
                sMeetingcheckrecode.setPValidity("已签到");
            }else if (sMeetingcheckrecode.getPValidity().equals("0")){
                sMeetingcheckrecode.setPValidity("未签到");
            }else  if(sMeetingcheckrecode.getPValidity().equals("2")){
                sMeetingcheckrecode.setPValidity("迟到");
            }else if (sMeetingcheckrecode.getPValidity().equals("3")){
                sMeetingcheckrecode.setPValidity("请假");
            }else if (sMeetingcheckrecode.getPValidity().equals("5")){
                sMeetingcheckrecode.setPValidity("审批中");
            }
        }
        Stream<SMeetingcheckrecode> notSign = singInEmployee.stream().filter(s -> s.getPValidity().equals("审批中"));
        if (singInEmployee.isEmpty()) {
            return ApiResult.fail("暂无审批员工");
        } else {
            return ApiResult.ok(notSign);
        }
    }
    //excel导出
    @GetMapping("/{mCode}")
    public void exportExcelPeopleNucleicEmployees(@PathVariable("mCode") String mCode,HttpServletResponse response)throws IOException {
        List<SMeetingcheckrecode> singInEmployee = meetingCheckRecodeService.findSignEmployee(mCode);
        for (SMeetingcheckrecode sMeetingcheckrecode : singInEmployee) {
            if(    sMeetingcheckrecode.getPValidity().equals("1")){
                sMeetingcheckrecode.setPValidity("已签到");
            }else if (sMeetingcheckrecode.getPValidity().equals("0")){
                sMeetingcheckrecode.setPValidity("未签到");
            }else  if(sMeetingcheckrecode.getPValidity().equals("2")){
                sMeetingcheckrecode.setPValidity("迟到");
            }else if (sMeetingcheckrecode.getPValidity().equals("3")){
                sMeetingcheckrecode.setPValidity("请假");
            }else if (sMeetingcheckrecode.getPValidity().equals("5")){
                sMeetingcheckrecode.setPValidity("审批中");
            }
        }
        String title = "签到记录";
        // 告诉浏览器用什么软件可以打开此文件
        response.setHeader("content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        // 下载文件的默认名称
        response.setHeader("Content-Disposition", "attachment;filename=" + RandomUtil.randomNumbers(4) + URLEncoder.encode("签到记录.xlsx","utf-8"));
        //4. 创建输入、输出流
        EasyExcel.write(response.getOutputStream(), SMeetingcheckrecode.class).sheet(title).doWrite(singInEmployee);
    }

    @GetMapping("findSingInEmployee")
    public ApiResult findSingInEmployee(String mCode) {
        List<EmployeeDto> singInEmployee = employeeDtoService.findSingInEmployee(mCode);
        List<EmployeeDto> collect = singInEmployee.stream().sorted(Comparator.comparing(EmployeeDto::getPBeginDate).reversed()).collect(Collectors.toList());
        if (singInEmployee.isEmpty()) {
            return ApiResult.fail("暂无签到员工");
        } else {
            return ApiResult.ok(collect);
        }
    }


    @GetMapping("getLateEmployee")
    public ApiResult getLateEmployee(String mCode) {
        log.info("获取迟到的员工姓名");
        if (employeeDtoService.selectLateEmployee(mCode).isEmpty()) {
            return ApiResult.fail("暂无迟到员工");
        } else {
            return ApiResult.ok();
        }
    }

    @GetMapping("getNotSingInEmployee")
    public ApiResult getNotSingInEmployee(String mCode) {
        List<EmployeeDto> employeeDtos = employeeDtoService.selectNotSingInEmployee(mCode);
        if (ObjectUtil.isEmpty(employeeDtos)) {
            return ApiResult.fail("暂无未签到人员");
        } else {
            return ApiResult.ok(employeeDtos);
        }

    }

    @GetMapping("getMeetQRName")
    public ApiResult getMeetQRName(String mCode) {
        Meeting meeting = meetingService.selectMeeting(mCode);
        if (ObjectUtil.isEmpty(meeting)) {
            return ApiResult.fail("暂无会议");
        } else {
            meeting.setQRCode(QRCodeUtil.getCode(meeting.getMCode()));
            return ApiResult.ok(meeting);
        }
    }

    @GetMapping("getMeetName")
    public ApiResult getMeetName(String mCode) {
        Meeting meeting = meetingService.selectMeeting(mCode);
        if (ObjectUtil.isEmpty(meeting)) {
            return ApiResult.fail("暂无会议");
        } else {
            return ApiResult.ok(meeting);
        }
    }

    @GetMapping("getMeetingList")
    public ApiResult getMeetingList(String startTime, String endTime) {
        List<Meeting> meetingList = meetingService.selectMeetingList(startTime, endTime);
        if (meetingList.isEmpty()) {
            return ApiResult.fail("暂无会议信息");
        }
        return ApiResult.ok(meetingList);
    }


    //查询所有部门下员工
    @GetMapping("deptList")
    public ResponseResult deptList() {
        List<MeetingEmployeeDto> list = deptService.queryAll();
        return new ResponseResult(200, list);
    }

    @GetMapping("img")
    public void deptImg(){
        deptService.getAll();

    }
    //删除
    @GetMapping("deleteOneSign")
    public ResponseResult delete(@RequestParam("mCode") String mCode,
                                 @RequestParam("iphone") String iphone){
        System.out.println(mCode+"====="+iphone);
        Integer one =  meetingCheckRecodeService.delete(mCode,iphone);

        return new ResponseResult(200,"成功");
    }

    //按组删除
    @PostMapping("deleteGroup")
    public ResponseResult deleteGroup(@RequestParam("mCode") String mCode,
                                      @RequestBody  List<MeetingEmployeeDto> dto){
        meetingEmployeeService.deleteGroup(mCode,dto);

        return new ResponseResult(200,"删除成功");
    }

    //会议提醒短信电话
    @GetMapping("sendSms")
    public ResponseResult sendSms(
            @RequestParam("mCode")String mCode,@RequestParam("iphone")String iphone
    ){
        meetingEmployeeService.send(mCode,iphone);
        return new ResponseResult(200,"短信发送成功");
    }
    //短信多条
    @PostMapping("batchMeetingSendSms")
    public ResponseResult batchMeetingSendSms(
            @RequestParam("mCode")String mCode,@RequestBody List<SMeetingcheckrecode> dto
    ){
        for (SMeetingcheckrecode sMeetingcheckrecode : dto) {
            meetingEmployeeService.send(mCode,sMeetingcheckrecode.getPPhone());
        }
        return new ResponseResult(200,"短信发送成功");
    }

    //添加
    @PostMapping("addOne")
    @Transactional
    public ResponseResult addOne(@RequestParam("mCode") String mCode,@RequestBody  List<MeetingEmployeeDto> dto){
        meetingEmployeeService.addList(mCode,dto);
        return new ResponseResult(200,"添加成功");
    }
    /**会议审批的接口*/
    @GetMapping("meetingApproval")
    public ApiResult meetingApproval(@RequestParam("mCode") String mCode,
                                     @RequestParam("emplCode")String emplCode,
                                     HttpServletRequest request
                                      ){
        String token = request.getHeader("token");
        String emplCodeMeeting;
        try {
            emplCodeMeeting = JWT.decode(token).getAudience().get(0);
        } catch (JWTDecodeException j) {
            throw new MyException(ResponseEnum.TOKEN_EX.getCode(), ResponseEnum.TOKEN_EX.getResultMessage());
        }
        Meeting meeting = meetingService.selectMeeting(mCode);
        if (meeting.getMOperCode()!=null&&meeting.getMOperCode().equals(emplCodeMeeting)){
            meetingService.meetingApproval(mCode, emplCode);
            return ApiResult.ok();
        }else {
            return ApiResult.fail("非会议创建人，暂无审批权限");
        }
    }


    @GetMapping("leaveNumber")
    public ApiResult leaveNumber(@RequestParam("mCode") String mCode){
        List<EmployeeDto> list = meetingService.leaveEmployeeNumber(mCode);
        return ApiResult.ok(list);
    }
    /**会议批量审批*/
    @PostMapping("batchMeetingApproval")
    public ApiResult batchMeetingApproval(HttpServletRequest request, @RequestParam("mCode")String mCode , @RequestBody List<SMeetingcheckrecode> dto){
        String token = request.getHeader("token");
        String emplCode;
        try {
            emplCode = JWT.decode(token).getAudience().get(0);
        } catch (JWTDecodeException j) {
            throw new MyException(ResponseEnum.TOKEN_EX.getCode(), ResponseEnum.TOKEN_EX.getResultMessage());
        }
        Meeting meeting = meetingService.selectMeeting(mCode);
        if (meeting.getMOperCode()!=null&&meeting.getMOperCode().equals(emplCode)){
            meetingService.batchMeetingApproval(mCode,dto);
            return ApiResult.ok("审批成功");
        }else {
            return ApiResult.fail("审批失败");
        }
    }



    @GetMapping("Recording")
    public ApiResult Recording(@RequestParam("mCode")String mCode ,@RequestParam("text") String text){
     meetingService.update(mCode,text);
     return ApiResult.ok();
    }

    //定时取
    @GetMapping("getTime")
    public ApiResult getTime(@RequestParam("mCode")String mCode ){
        return ApiResult.ok(redisService.getKeyObjectValue("text" + mCode, Integer.class));
    }

    //显示记录
    @GetMapping("text")
    public ApiResult getRecording(@RequestParam("mCode")String mCode ){

        Meeting meeting = meetingService.selectMeeting(mCode);
        System.out.println(meeting);
        if (meeting.getMText().equals(null)){
           return ApiResult.ok();
       }
        return ApiResult.ok(meeting.getMText());
    }
    //上传
    @PostMapping("read")
    public ApiResult upload(@RequestParam("mCode")String mCode,@RequestBody MultipartFile file) throws IOException {
        if (file.isEmpty()){
            return ApiResult.fail("上传失败请选择文件");
        }
        meetingService.addFile(mCode,file);

        return ApiResult.ok();
    }
    @PostMapping("getByte")
    public void getDow(@RequestParam("mCode")String mCode,HttpServletRequest req,HttpServletResponse response) throws IOException {
        try {
            // 输入流，通过输入流读取文件内容
            FileInputStream fileInputStream = new FileInputStream(new File(uploadFilePath + "dfcd38e7-710d-45f4-ac0b-f346328c57fb.docx"));
            // 输出流，通过输出流将文件写回浏览器，在浏览器展示图片
            ServletOutputStream outputStream = response.getOutputStream();
            //1.告诉浏览器文件类型是二进制
            response.setContentType("application/octet-stream");
            //2.告诉浏览器文件名
            response.setHeader("content-disposition","attachment;filename="+ URLEncoder.encode(uploadFilePath + "23067127-6708-4126-b665-05a2bd5af90b.docx","utf-8"));
            int len = 0;
            byte[] bytes = new byte[1024];
            while ((len = fileInputStream.read(bytes)) != -1) {
                outputStream.write(bytes, 0, len);
                outputStream.flush();
            } //3.告诉浏览器文件大小
            response.setContentLength(len);

            // 关闭资源
            outputStream.close();
            fileInputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }


    }


    @Value("${file.upload.url}")
    private String uploadFilePath;

    @PostMapping("file")
    public ApiResult upload(@RequestParam("mCode")String mCode,HttpServletRequest httpServletRequest, MultipartFile file) throws Exception {
        // 获取上传文件的原始文件名
        String originalFilename = file.getOriginalFilename();
//        // 获取原始文件名的后缀
//        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        // 使用UUID重新生成文件名，防止文件名称重复造成文件覆盖    会议号+文件名
        String fileName =mCode + originalFilename;


        // 创建一个目录对象
        File dir = new File(uploadFilePath);
        // 判断当前目录是否存在
        if (!dir.exists()) {
            // 目录不存在，需要创建
            dir.mkdirs();
        }
        Meeting meeting = meetingService.selectMeeting(mCode);
        if (!StringUtils.isBlank(meeting.getMRemark3())){
            File file1 = new File(meeting.getMRemark3());
        file1.delete();
        }


        try {
            // file是一个临时文件，需要转存到指定位置，否则本次请求完成后临时文件会被删除
            // basePath 是指定的保存路径，我们在上面声明了一个属性，属性值从yml配置文件读取，以便修改
            // 这里可能会有IO异常，我们需要把它抛出去
            file.transferTo(new File(uploadFilePath + fileName));
            meetingService.setFilePh(mCode,uploadFilePath + fileName);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return ApiResult.ok();

    }

    @GetMapping("Download")
    public void   Download(HttpServletResponse response, @RequestParam("mCode")String mCode) {
        try {
            Meeting meeting = meetingService.selectMeeting(mCode);
            // path是指欲下载的文件的路径。
            File file = new File(meeting.getMRemark3());


            // 取得文件名。
            String filename = file.getName();
            // 取得文件的后缀名。
            String ext = filename.substring(filename.lastIndexOf(".") + 1).toUpperCase();

            // 以流的形式下载文件。
            InputStream fis = new BufferedInputStream(new FileInputStream(meeting.getMRemark3()));
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            // 清空response
            response.reset();
            // 设置response的Header
            response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes()));
            response.addHeader("Content-Length", "" + file.length());
            OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/octet-stream");
            response.addHeader("Access-Control-Allow-Origin","*");
            toClient.write(buffer);
            toClient.flush();
            toClient.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }


    }
    @GetMapping("getFile")

    public void getFile(@RequestParam("mCode") String mCode,HttpServletResponse response){

        Meeting meeting = meetingService.selectMeeting(mCode);
        FileUtils.download(meeting.getMRemark3(),response);


    }



@GetMapping("getFileName")
public ApiResult getFileName(@RequestParam("mCode") String mCode){

    Meeting meeting = meetingService.selectMeeting(mCode);
    String substring = meeting.getMRemark3().substring(18);
    return ApiResult.ok(substring);
}


    @GetMapping("leave")
    public ApiResult leave(@RequestParam("mCode") String mCode){
        List<SMeetingcheckrecode> singInEmployee = meetingCheckRecodeService.findSignEmployee(mCode);
        for (SMeetingcheckrecode sMeetingcheckrecode : singInEmployee) {
            if(    sMeetingcheckrecode.getPValidity().equals("1")){
                sMeetingcheckrecode.setPValidity("已签到");
            }else if (sMeetingcheckrecode.getPValidity().equals("0")){
                sMeetingcheckrecode.setPValidity("未签到");
            }else  if(sMeetingcheckrecode.getPValidity().equals("2")){
                sMeetingcheckrecode.setPValidity("迟到");
            }else if (sMeetingcheckrecode.getPValidity().equals("3")){
                sMeetingcheckrecode.setPValidity("请假");
            }else if (sMeetingcheckrecode.getPValidity().equals("5")){
                sMeetingcheckrecode.setPValidity("审批中");
            }
        }
        Stream<SMeetingcheckrecode> notSign = singInEmployee.stream().filter(s -> s.getPValidity().equals("请假"));
        if (singInEmployee.isEmpty()) {
            return ApiResult.fail("暂无迟到员工");
        } else {
            return ApiResult.ok(notSign);
        }
    }

    @GetMapping("setMeetingFish")
    public ApiResult setMeetingFish(@RequestParam("mCode") String mCode,@RequestParam("time") int time){
        Meeting meeting = meetingService.selectMeeting(mCode);

        meetingService.setMeetingFish(mCode,time);
        return ApiResult.ok();
    }

    @GetMapping("setTwoSign")
    public ApiResult setTwoSign(@RequestParam ("mCode") String mCode){
        Meeting meeting = meetingService.selectMeeting(mCode);
        if (StringUtils.isBlank(meeting.getMEnd())){
            meeting.setMEnd("1");
            meeting.setMEndDate(new Date());
            meetingService.setTwoSign(meeting);
        }else {
            throw new RuntimeException("已设置二次签到,请勿重复设置");
        }
        return  ApiResult.ok();
    }
    @GetMapping("getTwoSign")
    public ApiResult getTwoSign(@RequestParam ("mCode") String mCode){
        Meeting meeting = meetingService.selectMeeting(mCode);
        return  ApiResult.ok(meeting);
    }

    //批量人员导入
    @PostMapping("importExcel")
    public ApiResult importExcel(@RequestBody MultipartFile file,@RequestParam ("mCode") String mCode){
        try {
            meetingService.importExcel(file,mCode);
        } catch (Exception e) {
            e.printStackTrace();
          return ApiResult.fail("导入失败");
        }



        return ApiResult.ok("导入成功");
    }

    //人员导入模板
    @PostMapping("templateExcel")
    public void templateExcel(HttpServletResponse response) throws IOException {
        ArrayList<OutsideEmployee> outsideEmployees = new ArrayList<>();
        String title = "院外人员导入模板";
        // 告诉浏览器用什么软件可以打开此文件
        response.setHeader("content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        // 下载文件的默认名称
        response.setHeader("Content-Disposition", "attachment;filename=" + RandomUtil.randomNumbers(4) + URLEncoder.encode("院外人员导入模板.xlsx","utf-8"));
        //4. 创建输入、输出流
        EasyExcel.write(response.getOutputStream(), OutsideEmployee.class).sheet(title).doWrite(outsideEmployees);

    }



}
